package chpt05;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.concurrent.TimeUnit;

// 输出时间任务：输出进入任务时间、任务持续时间gap、退出任务时间
public class TimePrinter implements Runnable {
	private DateTimeFormatter fmt;
	private Random rnd = new Random(5);

	public TimePrinter(String fmt) {
		this.fmt = DateTimeFormatter.ofPattern(fmt);
	}

	@Override
	public void run() {
		LocalDateTime now = LocalDateTime.now();
		System.out.print("in = "+now.format(fmt)); // 按照fmt格式化
		// 底下的代码让当前任务随机休眠一段时间(1-3秒之间)
		int gap = rnd.nextInt(3) + 1;    // 返回[1, 3]之间的随机整数
		try {
			TimeUnit.SECONDS.sleep(gap); // 休眠gap时间
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		now = LocalDateTime.now();
		System.out.println(", gap = "+ gap + ", out = " + now.format(fmt));
	}
}
